package com.jacky.sso.service.impl;

import com.jacky.sso.entities.SysPermission;
import com.jacky.sso.entities.SysRolePermission;
import com.jacky.sso.entities.SysUser;
import com.jacky.sso.entities.SysUserRole;
import com.jacky.sso.reposities.SysPermissionRepository;
import com.jacky.sso.reposities.SysRolePermissionRepository;
import com.jacky.sso.reposities.SysUserRepository;
import com.jacky.sso.reposities.SysUserRoleRepository;
import com.jacky.sso.service.IPermissionService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class PermissionServiceImpl implements IPermissionService {

    @Resource
    private SysRolePermissionRepository sysRolePermissionRepository;
    @Resource
    private SysPermissionRepository sysPermissionRepository;
    @Resource
    private SysUserRoleRepository sysUserRoleRepository;


    @Override
    public List<SysPermission> findByUserId(Integer userId) {
        List<SysUserRole> userRoles = sysUserRoleRepository.findByUserId(userId);
        if (CollectionUtils.isEmpty(userRoles)) {
            return null;
        }
        List<Integer> roleIds = userRoles.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
        List<SysRolePermission> rolePermissions = sysRolePermissionRepository.findByRoleIds(roleIds);
        if (CollectionUtils.isEmpty(rolePermissions)) {
            return null;
        }
        List<Integer> permissionIds = rolePermissions.stream().map(SysRolePermission::getPermissionId).distinct().collect(Collectors.toList());
        List<SysPermission> permissions = sysPermissionRepository.findByIds(permissionIds);
        if (CollectionUtils.isEmpty(permissions)) {
            return null;
        }
        return permissions;
    }
}
